package cn.tedu.csmall.product.filter;

import cn.tedu.csmall.product.security.LoginPrincipal;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * JWT认证过滤器
 *
 * <p>Spring Security框架会自动从SecurityContext读取认证信息，如果存在有效信息，则视为已登录，否则，视为未登录</p>
 * <p>当前过滤器应该尝试解析客户端可能携带的JWT，如果解析成功，则创建对应的认证信息，并存储到SecurityContext中</p>
 *
 * @author liuweitao
 * @version 1.0.0
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    @Value("${csmall.jwt.secret-key}")
    String secretKey;

    public final static int JWT_MIN_LENGTH = 100;

    /**
     * 发送错误信息
     *
     * @param response 响应
     * @param serviceCode 异常状态码
     * @param message 错误信息
     * @throws IOException 抛出异常
     */
    private void sendErrMessage(HttpServletResponse response, ServiceCode serviceCode, String message) throws IOException {
        PrintWriter pw = response.getWriter();
        JsonResult jsonResult = JsonResult.fail(serviceCode,message);
        //需要使用fastjson依赖，将对象toString的字符串内容格式转换成JSON对象字符串内容格式
        String jsonResultString = JSON.toJSONString(jsonResult);
        pw.println(jsonResultString);
        pw.close();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 清除SecurityContext中原有的数据（认证信息）,每次都要预检
        SecurityContextHolder.clearContext();

        String jwt = request.getHeader("Authorization");
        log.debug("接收到JWT数据：{}",jwt);

        // 判断是否获取到有效的JWT
        // hasText()null,empty,是否为文本
        if(!StringUtils.hasText(jwt) || jwt.length() < JWT_MIN_LENGTH){
            //直接放行
            log.debug("未获取到有效的JWT数据，将直接放行");
            filterChain.doFilter(request,response);
            return;
        }

        //设置响应的文档类型
        response.setContentType("application/json; charset=utf-8");

        // 尝试解析JWT，从中获取用户的相关数据，例如id、username等
        log.debug("将尝试解析JWT...");
//        String secretKey = "asdfasdfasdfJJSADJFWE";

        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
        } catch (SignatureException e){
            String message = "非法访问";
            sendErrMessage(response,ServiceCode.ERR_JWT_SIGNATURE,message);
            return;
        }catch (MalformedJwtException e){
            String message = "非法访问";
            sendErrMessage(response,ServiceCode.ERR_JWT_MALFORMED,message);
            return;
        }catch (ExpiredJwtException e){
            String message = "登录已过期，请重写登录";
            sendErrMessage(response,ServiceCode.ERR_JWT_EXPIRED,message);
            return;
        }catch (Throwable e){
            String message = "未知错误";
            e.printStackTrace();
            sendErrMessage(response,ServiceCode.ERR_UNKNOWN,message);
            return;
        }

        // 准备用于创建认证信息的权限数据
        String authoritiesJsonString = claims.get("authorities",String.class);
        //将JsonString的Json类型字符串转换成对应的ArrayList类型，成员的类为SimpleGrantedAuthority.class
        List<SimpleGrantedAuthority> authorities = JSON.parseArray(authoritiesJsonString, SimpleGrantedAuthority.class);
        log.debug("从JWT中解析得到数据：authoritiesJsonString={}",authoritiesJsonString);
        log.debug("从JWT中解析得到数据：authorities={}",authorities);
        log.debug("从JWT中解析得到数据：authorities类名={}",authorities.getClass().getName());
        log.debug("从JWT中解析得到数据：authorities中数值下标0={}",authorities.get(0));
        log.debug("从JWT中解析得到数据：authorities中数值下标0的类名={}",authorities.get(0).getClass().getName());
        /*List<GrantedAuthority> authorities = new ArrayList<>();
        GrantedAuthority authority = new SimpleGrantedAuthority("这是山寨的权限标识");
        authorities.add(authority);*/

        //准备用于创建认证信息的当事人数据
        Long id = claims.get("id", Long.class);
        String username = claims.get("username", String.class);
        log.debug("从JWT中解析得到数据：id={}",id);
        log.debug("从JWT中解析得到数据：username={}",username);
        LoginPrincipal loginPrincipal = new LoginPrincipal();
        loginPrincipal.setId(id).setUsername(username);

        //创建认证信息
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginPrincipal,null,authorities);//放置当事人，密码，权限

        // 将认证信息存储到SecurityContext中,Spring Security框架会自动从SecurityContext读取认证信息，如果存在有效信息，则视为已登录，否则，视为未登录,拦截
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        //放行
        log.debug("获取到有效的JWT数据，放行");
        filterChain.doFilter(request,response);
    }
}
